// +----------------------------------------------------------------------
// | Cmshongshi [ 鸿时互娱管理系统 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2018 http://www.hongshihuyu.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: wgh
// +----------------------------------------------------------------------
const crypto = require('crypto');
const fs = require('fs');
module.exports = class extends think.cmswing.center {
  /**
   * index action
   * @return {Promise} []
   */
  indexAction() {
    // auto render template file index_index.html
    return this.display();
  }
  // 支付
  async payAction() {
    // 判断是否登录
    if (!this.is_login) {
      // 判断浏览客户端
      if (this.isMobile) {
        // 手机端直接跳转到登录页面
        return this.redirect('/center/public/login');
      } else {
        return this.redirect('/cmswing/error/login');
      }
    }
    
    if (this.isAjax('post')) {
      let payment;
      let pay;
      let charges;
      const post = this.post();
      let data = post;
      // 获取订单信息
      const order = await this.model('order').where({pay_status: 0, user_id: this.user.uid}).find(post.order_id);
      if (think.isEmpty(order)) {
        return this.fail('订单不存在！');
      }
      
      // 支付日志
      const receiving = {
        order_id: post.order_id,
        user_id: this.user.uid,
        amount: order.order_amount,
        create_time: new Date().getTime(),
        payment_time: new Date().getTime(),
        doc_type: 0,
        payment_id: post.payment,
        pay_status: 0
      };

      // 100预付款支付

      if (post.payment == 100) {
        // 先检查下用户余额
        const balance = await this.model('member').where({user_id: this.user.uid}).getField('amount', true);
        if (Number(balance) < Number(order.order_amount)) {
          return this.fail('您余额不足，请充值，或者选择其他支付方式！');
        } else {
          // 扣款
          const decrement = this.model('member').where({user_id: this.user.uid}).decrement('amount', Number(order.order_amount));
          if (decrement) {
            // 扣款成功改变订单状态
            await this.model('order').where({order_no: order.order_no}).update({status: 3, pay_status: 1});
            // 扣款成功后插入日志
            const log = {
              admin_id: 0,
              user_id: this.user.uid,
              type: 2,
              time: new Date().valueOf(),
              amount: (0 - Number(order.order_amount)),
              amount_log: await this.model('member').where({id: this.user.uid}).getField('amount', true),
              note: `${await get_nickname(this.user.uid)} 通过余额支付方式进行商品购买,订单编号：${order.order_no}`
            };
            await this.model('balance_log').add(log);
            receiving.pay_status = 1;
            await this.model('doc_receiving').add(receiving);
            const url = `/center/pay/payres/?c_o_id=${post.order_id}`;
            return this.success({name: '支付订单对接成功，正在转跳！', url: url});
          } else {
            return this.fail('您没有要支付的订单');
          }
        }
      }
      if (post.payment == 1001) {
        const url = `/center/pay/payres/?c_o_id=${post.order_id}`;
        return this.success({name: '支付订单对接成功，正在转跳！', url: url});
      }
      // 1001货到付款
      if (think.isEmpty(order)) {
        return this.fail('您没有要支付的订单');
      } else {
        // 判断是否已经绑定pingxx_id,如果已绑定查询pingxx订单直接支付。防止订单重复生成。
        // console.log(order.id);
        if (think.isEmpty(order.pingxx_id)) {
        
          // 获取渠道
          
          const parter = '200073';
      	  const key = '1o4ur5fdzbzppr3nndgvdf1ptv7dwevn';
      	  const serverUrl = 'http://www.yinfupay.net/Pay_Index.html';
      	  const callbackUrl = 'http://www.hongshihuyu.com/center/pay/notify';
      	  const hrefbackUrl = 'http://www.hongshihuyu.com/center/pay/result';
          
      	  const channel = await this.model('pingxx').where({id:data.payment}).getField('channel', true);//'6001'
            
      	  var money=order.order_amount;
          var orderId=order.order_no;
//            var payerIp=this.ip();
            var payerIp='';
            var attach = '';
            for (var i = 0; i < 8; i++) {
          	  attach += Math.floor(Math.random() * 10);
            }
            //var signStr='parter='+parter+'&type='+channel+'&value='+money+'&orderid='+orderId+'&callbackurl='+callbackUrl+key;
            var pay_applydate=this.moment(new Date().valueOf()).format('YYYY-MM-DD HH:mm:ss')
  		    var signStr='pay_amount='+money+'&pay_applydate='+pay_applydate+'&pay_bankcode='+channel+'&pay_callbackurl='+hrefbackUrl+'/'+orderId+'&pay_memberid='+parter+'&pay_notifyurl='+callbackUrl+'&pay_orderid='+orderId+'&key='+key;
  			console.log('signStr---------:'+signStr);
  			signStr=think.md5(signStr);
  			console.log('signStr md5---------:'+signStr);
  			signStr=signStr.toUpperCase();
  			console.log('signStr toUpperCase---------:'+signStr);
            
            data.parter=parter;
            data.channel=channel;
            data.money=money;
            data.orderId=orderId;
            data.callbackurl=callbackUrl;
            data.hrefbackurl=hrefbackUrl+'/'+orderId;
            data.key=key;
            data.serverUrl=serverUrl;
            data.payerIp=payerIp;
            data.attach =attach;
            data.pay_applydate=pay_applydate;
			data.productname = "流量点卡";
            data.sign = signStr;
        } 
        // console.log(charges);
        if (data) {
          // 更新订单的sign取值
          //await this.model('order').where({id: order.id}).update({sign:data.sign});
          
          // 更新订单的支付方式,sign,attach
          await this.model('order').where({id: order.id}).update({payment: data.payment,sign:data.sign,attach:data.attach});

          await this.model('doc_receiving').add(receiving);
          return this.success({name: '支付订单对接成功，正在转跳！', data: data});
        } else {
          return this.fail('调用接口失败！');
        }
      }
      
    } else {
      const order_id = this.get('order');
      const setp = this.get('setp') || '';
      // this.end(order_id  + "=" + setp)
      // 订单信息
      const order = await this.model('order').where({pay_status: 0, user_id: this.user.uid}).find(order_id);
      if (think.isEmpty(order)) {
        const error = this.controller('cmswing/error');
        return error.noAction('订单不存在或者已经支付！');
      }
      order.end_time = date_from(order.create_time + (Number(this.config('setup.ORDER_DELAY')) * 60000));
      // console.log(order);
      this.assign('order', order);

      //   //支付方式
      // let paylist = await this.model("payment").where({status:1}).order("sort ASC").select();
      // for(let val of paylist){
      //      val.logo =  await this.model("pay_plugin").where({id:val.plugin_id}).getField("logo",true);
      //   }
      //   this.assign("paylist",paylist);
      // 根据不同的客户端调用不同的支付方式
      let map;
      if (this.isMobile) {
          map = {
        		  type: 6,
                  status: 1,
                  agent:'yinfupay'
          };
          if (!this.isweixin) {
            map.channel = ['!=', 'wx_pub'];
          }
        } else {
          map = {
            type: 1,
            status: 1
          };
      }
      
      const paylist = await this.model('pingxx').where(map).order('sort ASC').select();
      this.assign('paylist', paylist);
      this.assign('setp', setp);
      this.meta_title = '订单支付';// 标题1
      this.keywords = this.config('setup.WEB_SITE_KEYWORD') ? this.config('setup.WEB_SITE_KEYWORD') : '';// seo关键词
      this.description = this.config('setup.WEB_SITE_DESCRIPTION') ? this.config('setup.WEB_SITE_DESCRIPTION') : '';// seo描述
      const balance_amount = await this.model('member').where({id: this.user.uid}).getField('amount', true);
      
      this.assign('balance_amount', balance_amount); 
      // 判断浏览客户端
      if (this.isMobile) {
        return this.display(this.mtpl());
      } else {
        return this.display();
      }
    }
  }
  // Webhooks
  async webhooksAction() {
    const data = this.post();
    // 验证 webhooks 签名
    var verify_signature = function(raw_data, signature, pub_key_path) {
      var verifier = crypto.createVerify('RSA-SHA256').update(raw_data, 'utf8');
      var pub_key = fs.readFileSync(pub_key_path, 'utf8');
      return verifier.verify(pub_key, signature, 'base64');
    };

    // POST 原始请求数据是待验签数据，请根据实际情况获取
    var raw_data = JSON.stringify(data);
    // 签名在头部信息的 x-pingplusplus-signature 字段
    var signature = this.header('x-pingplusplus-signature');
    // 请从 https://dashboard.pingxx.com 获取「Webhooks 验证 Ping++ 公钥」
    var pub_key_path = think.ROOT_PATH + '/private/pingpp/pingpp_rsa_public_key.pem';

    if (!verify_signature(raw_data, signature, pub_key_path, fs, crypto)) {
      return this.fail('服务其验证失败！');
    }

    switch (data.type) {
      case 'charge.succeeded':
        // 开发者在此处加入对支付异步通知的处理代码
        // console.log(data.data.object.paid);
        if (data.data.object.paid) {
          const order = await this.model('order').where({order_no: data.data.object.order_no}).find();
          // 支付成功改变订单状态
          const update = await this.model('order').where({order_no: data.data.object.order_no}).update({status: 3, pay_status: 1, pay_time: (data.data.object.time_paid * 1000)});
          if (order.type == 1 && update) {
            await this.model('member').where({id: order.user_id}).increment('amount', order.order_amount);
            // 充值成功后插入日志
            const log = {
              admin_id: 0,
              user_id: order.user_id,
              type: 2,
              time: new Date().valueOf(),
              amount: Number(order.order_amount),
              amount_log: await this.model('member').where({id: order.user_id}).getField('amount', true),
              note: `${await get_nickname(order.user_id)} 通过[${await this.model('pingxx').where({id: order.payment}).getField('title', true)}]支付方式进行充值,订单编号：${data.data.object.order_no}`
            };
            await this.model('balance_log').add(log);
          }
          // 记录支付日志
          await this.model('doc_receiving').where({order_id: order.id}).update({pay_status: 1, payment_time: (data.data.object.time_paid * 1000)});
          this.success({name: '成功！'});
        } else {
          this.fail('失败！');
        }
        break;
      case 'refund.succeeded':
        // 开发者在此处加入对退款异步通知的处理代码sfdsfs
        break;
      default:
    }
  }
  // 后端支付回调
  async notifyAction() {
    const code = this.post();
    // orderId: '1458722092073', respMsg: 'success'
    console.log('代理端支付回调code--1:'+JSON.stringify(code));
    // 支付接口回掉
    console.log('代理端支付回调code--3:'+code.orderid);
    const order = await this.model('order').where({order_no: code.orderid}).find();
    if(!think.isEmpty(order)){
      console.log('代理端支付支付回调code.attach--:'+code.attach);
      if(code.attach==order.attach){
        if(code.returncode=='00'){
          console.log('代理端支付回调order.pay_status--:'+order.pay_status);
          if(order.pay_status == 0) {
        // 支付成功改变订单状态 code.systime
    	//var time_paid = (new Date(code.systime)).getTime();
    	//var completiontime = (new Date(code.completiontime)).getTime();
        var time_paid = (new Date()).getTime();
        var completiontime = (new Date()).getTime();
    	console.log('代理端支付回调time_paid--5:'+time_paid);
    	console.log('代理端支付回调completiontime--5:'+completiontime);
        const update = await this.model('order').where({order_no:code.orderid}).update({status:4,pay_status:1,notify_remark:"支付成功",delivery_status:1,pay_time:time_paid,completion_time:completiontime,pingxx_id:code.transaction_id});

        if (update) {
          if (order.type == 1) {
          await this.model('member').where({id: order.user_id}).increment('amount', order.order_amount);
          console.log('代理端支付回调time_paid--6:'+time_paid);
          // 充值成功后插入日志
          const log = {
            admin_id: 0,
            user_id: order.user_id,
            type: 2,
            time: new Date().valueOf(),
            amount: Number(order.order_amount),
            amount_log: await this.model('member').where({id: order.user_id}).getField('amount', true),
            note: `${await get_nickname(order.user_id)} 通过[${await this.model('pingxx').where({id: order.payment}).getField('title', true)}]支付方式进行充值,订单编号：${order.order_no}`
          };
          await this.model('balance_log').add(log);
          console.log('代理端支付回调code--7:'+code.orderid);
          }else if(order.type == 0){
        	  console.log('代理端支付回调code--7:'+code.orderid);
        	  let goodsremark = '';
        	  let cointotal = 0;
        	  let goodnoList = await this.model('order_goods').where({order_id:order.id}).field('goods_no,goods_nums').select();
//        	  console.log('goodnoList--1:'+JSON.stringify(goodnoList));
        	  if (!think.isEmpty(goodnoList)) {
        		  for (const val of goodnoList) {
        			  if(!think.isEmpty(val.goods_no)){
        				  const goodnos = val.goods_no.split('_');
        				  if(goodnos.length>1){
        					  let tgns = Number(goodnos[1])*Number(val.goods_nums);
        					  if(goodnos[0]=='card'){
        						  if(think.isEmpty(goodsremark)){
        							  goodsremark+='房卡:'+tgns+'张';
        						  }else{
        							  goodsremark+=',房卡:'+tgns+'张';
        						  }
        					  }else if(goodnos[0]=='coin'){
        						  cointotal=Number(cointotal)+Number(tgns);
        						  if(think.isEmpty(goodsremark)){
        							  goodsremark+='金币:'+tgns+'枚';
        						  }else{
        							  goodsremark+=',金币:'+tgns+'枚';
        						  }
        					  }
        					 await this.model('member').where({id: order.user_id}).increment(goodnos[0]+'_count',tgns);
        				  }
        			  }
        		  }
        	  }
        	  //SAFEBOX_MIN_COIN_NUM
        	  var mincoinnum = this.config('setup.SAFEBOX_MIN_COIN_NUM') ? this.config('setup.SAFEBOX_MIN_COIN_NUM') :100;
        	  const member = await this.model('member').where({id:order.user_id}).field('coin_count,safebox').find();
        	  if(!think.isEmpty(member)
        		&&member.safebox==0
        		&&Number(member.coin_count)>=Number(mincoinnum)){
        		await this.model('member').where({id:order.user_id}).update({safebox:1});
        	  }
        		
        	//0:账户充值，1:提现,2:订单,3:充卡,4:充币,5:返利
              const log = {
                admin_id: 0,
                user_id: order.user_id,
                type: 2,
                time: new Date().valueOf(),
                amount: Number(order.order_amount),
                amount_log:Number(order.order_amount),
                note: `${await get_nickname(order.user_id)} 通过[${await this.model('pingxx').where({id: order.payment}).getField('title', true)}]支付方式进行交易，购买[${goodsremark}],订单编号：${order.order_no}`
              };
              await this.model('balance_log').add(log);
          }
        // 记录支付日志
        await this.model('doc_receiving').where({order_id: order.id}).update({pay_status: 1, payment_time: (time_paid)});
        }
        
       }
       if (order.pay_status == 0&& order.type == 1) {
         await this.model('order').where({order_no: order.order_no}).delete();
       }
       return this.body = 'OK';
      }else{
        let notify_remark =(code.returncode==-1?"请求参数无效":"签名错误");
        await this.model('order').where({order_no:code.orderid}).update({status:4,pay_status:-1,notify_remark:notify_remark,pay_time:time_paid,completion_time:completiontime,pingxx_id:code.transaction_id});
        // 记录支付日志
        await this.model('doc_receiving').where({order_id: order.id}).update({pay_status:-1, payment_time: (time_paid)});
         
        return this.body = 'NO';
      }
      }else{
        console.log('代理端支付code.attach--错误!');
        return this.body = 'NO';
      }
    }else{
      console.log('代理端支付code.orderid--错误!');
       return this.body = 'NO';
    }
 }
  
  //http://www.hongshihuyu.com/center/pay/result/022018093006908aba88  orderid
  async resultAction() {
    const code = this.post();
    console.log('代理端支付 支付页面跳转 code--:'+JSON.stringify(code));
    //const orderid = this.get('orderid') || 0;
    //console.log('orderid--:'+code.orderid)
    //code.orderid = orderid;
    console.log('代理端支付 支付页面 code.orderid--:'+code.orderid);
    // 支付回掉
    if(!think.isEmpty(code.orderid)) {
      const order = await this.model('order').where({order_no:code.orderid}).find();
      
      this.assign('order', order);
    } 
    this.meta_title = '支付结果';// 标题1
    // 判断浏览客户端
    if (this.isMobile) {
      return this.display(this.mtpl());
    } else {
      return this.display();
    }
  }
  
  // 凯瑞支付回调
  async krpayresAction() {
    const code = this.get();

    // orderId: '1458722092073', respMsg: 'success'
    console.log('kr支付回调code--:'+code);
    // 站内支付回掉
    if (code.orderid) {
      const order = await this.model('order').find(code.orderid);
      order.amount = order.order_amount;
      switch (order.payment) {
        case 100:
          order.channel = '预付款支付';
          break;
        default:
          order.channel = '货到付款';
          break;
      }
      this.assign('order', order);
      return this.success({opstate:code.opstate});
    } 

    this.meta_title = '支付结果';// 标题1
    this.keywords = this.config('setup.WEB_SITE_KEYWORD') ? this.config('setup.WEB_SITE_KEYWORD') : '';// seo关键词
    this.description = this.config('setup.WEB_SITE_DESCRIPTION') ? this.config('setup.WEB_SITE_DESCRIPTION') : '';// seo描述
    // 判断浏览客户端
    if (this.isMobile) {
      return this.display(this.mtpl());
    } else {
      return this.display();
    }
  }
  

};
